<template>
  <el-dialog :title="title" :visible.sync="dialogVisible" :before-close="handleClose">
    <div class="wrapper">
      <div class="input-row">
        <el-form :inline="true" :model="formInline" @submit.native.prevent>
          <el-form-item label="关键词">
            <el-input size="small" clearable v-model="formInline.keyword" @keyup.native.enter="handleFilter" />
          </el-form-item>
          <el-form-item label="变量分类">
            <el-select v-model="formInline.variableType" size="small" placeholder="请选择" clearable>
              <el-option v-for="item in classifyList" :key="item.id" :value="item.id" :label="item.name">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter" size="small">查询</el-button>
            <el-button @click="resetQuery" size="small">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table :data="tableData" class="ins-table" max-height="500" v-loading="loading">
        <el-table-column prop="variableName" label="变量名称">
        </el-table-column>
        <el-table-column prop="variableType" label="变量类型">
        </el-table-column>
        <el-table-column prop="variableCode" label="变量编码">
        </el-table-column>
        <el-table-column width="100" label="操作">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="insert(scope.row)"
              :disabled="editType=='document' && scope.row?.variableConfig?.variableViewType != 'variable_string_quote'">插入</el-button></template>
        </el-table-column>
      </el-table>

      <el-pagination v-if="total" layout="prev, pager, next" :page-size="10" :total="total"
        :current-page.sync="queryParams.pageNum" @current-change="handleCurrentChange">
      </el-pagination>
    </div>
  </el-dialog>
</template>

<script>
  import { v4 as uuid } from "uuid";
  import store from "@/store";
  import tinymce from "tinymce/tinymce";
  import { addSpecialPage } from "@/utils/commands/addPage";
  import { getDocumentVariableList } from "@/api/variable";
  export default {
    name: "VariableDialog",
    data() {
      return {
        total: 0,
        currentPage: 1,
        tableData: [],
        cascaderData: [],
        blockTypeMap: {},
        formInline: {
          keyword: "",
          variableCode: "",
          variableNamespace: "",
          variableType: "",
        },
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        dialogVisible: false,
        title: "变量",
        loading: false,
        editType: this.$store.state.xmleditor.editorConfig.editContentType
      };
    },
    computed: {
      insertType() {
        return this.$store.state.xmleditor.insertType;
      },
      classifyList() {
        return this.$store.state.xmleditor.classifyList;
      },
    },
    mounted() {
      this.handleFilter();
    },
    methods: {
      resetQuery() {
        this.queryParams.pageNum = 1;
        this.formInline = {
          keyword: "",
          variableCode: "",
          variableNamespace: "",
          variableType: "",
        };
        this.handleFilter();
      },
      show() {
        this.resetQuery();
        this.dialogVisible = true;
      },
      async handleFilter() {
        //接口查询变量列表数据
        try {
          this.loading = true;
          const res = await getDocumentVariableList({
            ...this.queryParams,
            ...this.formInline,
          });
          this.tableData = res.data.list || [];
          this.total = res.data.count;
          //查询章节数据
          let queryId = null;
          await res.data.list.map(item => {
            if (item.variableConfig?.variableViewType == 'variable_chapt') {
              queryId = item.id;
            }
          })
          this.$store.commit('xmleditor/SET_VARIABLE_CHARPT_ID', queryId)
        } catch {
          console.log("error");
        } finally {
          this.loading = false;
        }
      },
      handleCurrentChange(currentPage) {
        this.queryParams.pageNum = currentPage;
        this.handleFilter();
      },
      getClassifyName(row) {
        if (this.insertType === "block") {
          return this.blockTypeMap[row.variableType];
        }
        return (
          this.classifyList.find((i) => i.id === row.variableType)?.variableName || ""
        );
      },
      async handleConfirm() { },
      async insert(row) {
        const dataId = uuid();
        const content = row.variableName;
        setTimeout(async() => {
          // 算例模板
          if (row?.variableConfig.variableViewType === "variable_chapt") {
            addSpecialPage(27, "强度分析", row?.id);
            store.commit("xmleditor/UPDATE_DOC_STRUCTURE");
            this.handleClose();
            tinymce.activeEditor.notificationManager.open({
              timeout: 1500,
              text: "插入成功!",
              type: "success",
            });
            return;
          }
          if (row?.variableConfig.variableViewType.includes("variable_table")) {
            const captions = tinymce.activeEditor.getDoc()?.querySelectorAll(`[class="caption zh"]`) || [];
            let maxNumber = 1;
            if (captions.length > 0) {
              maxNumber = captions[captions.length - 1].getAttribute('data-number');
              maxNumber = Number.parseInt(maxNumber);
              maxNumber += 1;
            }

            tinymce.activeEditor.insertContent(
              `<table border="1" class="data-content-table " data-type="table" data-variable-id=${row.id} data-block-id="${uuid()}" data-id="${dataId}" style="border-collapse: collapse; width: 98.0521%;" data-mce-selected="1">
              <caption data-id="${uuid()}" class="table_caption zh">
                <p class="caption zh" data-number="${maxNumber}">${row.variableName}</p>
              </caption>
              <thead>
                <tr>
                  <td>
                    <p data-id="${uuid()}" data-block-id="${uuid()}" data-type="paragraph">​</p>
                  </td>
                  <td>
                    <p data-id="${uuid()}" data-block-id="${uuid()}" data-type="paragraph">​</p>
                  </td>
                </tr>
              </thead>
		          <tbody>
                <tr>
                  <td>
                    <p data-id="${uuid()}" data-block-id="${uuid()}" data-type="paragraph">​</p>
                  </td>
                  <td>
                    <p data-id="${uuid()}" data-block-id="${uuid()}" data-type="paragraph">​</p>
                  </td>
                </tr>
              </tbody>
            </table>`
            )
            // if(row?.variableConfig.variableViewType.includes("variable_table_meterial")){
            //   tinymce.activeEditor.insertContent(`<p data-type="empty_block"></p>`)
            // }
            store.commit("xmleditor/UPDATE_DOC_STRUCTURE");
            this.handleClose();
            return;
          }
          //判断是否有相同的引用文件变量
          console.log("条件判断")
          console.log(row?.variableConfig.variableViewType.includes("variable_string_quote") && this.editType == 'document')
          let insertFlag = true;
          if (row?.variableConfig.variableViewType.includes("variable_string_quote") && this.editType == 'document') {
            const el = tinymce.activeEditor.getDoc()?.querySelectorAll(`[data-variable-id="${row.id}"]`);
            console.log(el)
            if (el.length>0) {
             await this.$confirm('应用文件变量已存在，是否继续插入', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                  console.log("");
              }).catch(() => { 
                insertFlag = false;
              });
            }
          }
          if(!insertFlag){
            return;
          }
          // 字符串插入
          tinymce.activeEditor.selection.setContent(
            `<span data-type="${row?.variableConfig.variableViewType}" data-id=${dataId} data-variable-id=${row.id} style="font-style: italic;text-decoration: underline;color: blue;">${content}</span>`
          );
          const currentNode = tinymce.activeEditor.dom.select(`[data-id="${dataId}"]`);
          currentNode[0].dataset.variableId = row.id;
          tinymce.activeEditor.selection.setContent(" ");
          store.commit("xmleditor/UPDATE_DOC_STRUCTURE");
          this.handleClose();
          tinymce.activeEditor.notificationManager.open({
            timeout: 1500,
            text: "插入成功!",
            type: "success",
          });
        });
      },
      handleClose() {
        this.dialogVisible = false;
      },
    },
  };
</script>

<style scoped>
  .variable-class {
    font-style: italic;
    text-decoration: underline;
    color: blue;
  }

  .ins-table {
    width: 100%;
  }

  ::v-deep .el-dialog {
    min-width: 800px;
  }

  ::v-deep .el-dialog__body {
    padding-top: 0;
    padding-bottom: 10px;
  }
</style>